package controllers;

import forms.UserForm;

import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import data.BlogData;
import data.UserData;
import debugs.UserDebug;

import models.Blog;
import models.User;

public class ViewProfileServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		
		String gmail = request.getUserPrincipal().getName();
		//Get list user
		ArrayList<User> users = new ArrayList<User>();
		
		//Get blogs by gmail
		BlogData bData =  new BlogData();
		ArrayList<Blog> blogs = bData.getAllByGmail(gmail);
		
		TreeMap check = new TreeMap();
		request.setAttribute("blogs", blogs);
		request.setAttribute("users", users);
		request.setAttribute("form", "edit");
		request.setAttribute("check", check);
		try {
            request.getRequestDispatcher("/pages/form_profile.jsp").forward(request, response);
        } catch (Exception e) {
            //TODO: handle exception
            e.printStackTrace();
        }
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) 
		throws IOException {
		String gmail = request.getUserPrincipal().getName();
		
		//Get list user
		ArrayList<User> users = new ArrayList<User>();
		
		//Get blogs by gmail
		BlogData bData =  new BlogData();
		ArrayList<Blog> blogs = bData.getAllByGmail(gmail);
		
		UserData uData = new UserData();
		User user = (User) request.getAttribute("user");
		
		//Get value form and check valid
		TreeMap form = UserForm.checkValid(request, user);
		user =(User) form.get("user");
		TreeMap check = (TreeMap) form.get("checkValid");
		
		//Save data
		if (check.size() == 0){
			uData.insert(user);
//			AutoSiteDebug.debug(autoSite);
			request.setAttribute("success", "Update success profile " + user.getGmail());
		}
		
		request.setAttribute("blogs", blogs);
		request.setAttribute("user", user);
		request.setAttribute("users", users);
		request.setAttribute("form", "edit");
		request.setAttribute("check", check);
		try {
            request.getRequestDispatcher("/pages/form_profile.jsp").forward(request, response);
        } catch (Exception e) {
            //TODO: handle exception
            e.printStackTrace();
        }
	}
}
